// TcpClient.cc

#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"

enum
{
    UsageError = 1,
    SockerError,
    BindError,
    ListenError
};

void Usage(const std::string &proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n"
              << std::endl;
    ;
}

// ./tcpclient serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    // tcp客户端要不要bind？要，但不用显式bind，系统随机选择端口号进行绑定
    // 客户端发起connect的时候，进行自动随机绑定
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(server.sin_family, serverip.c_str(), &server.sin_addr);

    std::string message; // 保存要发送的数据
    char inbuffer[4096]; // 保存接收到的数据
    while (true)
    {
        // 1.创建套接字
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            std::cerr << "socket create error" << std::endl;
            return 1;
        }
        // std::cout << "sockfd: " << sockfd << std::endl;  // 测试

        int cnt = 5;
        bool isreconnect = false;
        do
        {
            // 2.连接
            int c = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
            if (c < 0)
            {
                isreconnect = true;
                --cnt;
                std::cerr << "connect error..., reconnect: " << cnt << std::endl;
                sleep(1);
                // return 2;
            }
            else
            {
                break;
            }
        } while (cnt && isreconnect);

        if (cnt == 0)
        {
            std::cerr << "user offline..." << std::endl;
            break;
        }

        // while (true)
        // {
            // 3.通信
            std::cout << "Please Enter# ";
            std::getline(std::cin, message); // getline不接收最后的'\n'
            if (message.size() == 0) continue;  // 字符串为空时，write写入会出问题
            int m = write(sockfd, message.c_str(), message.size());
            if (m < 0)
            {
                std::cerr << "write error..." << std::endl;
                close(sockfd);
                continue;
                // break;
            }
            // std::cout << "write return: " << m << std::endl;  // 测试

            ssize_t n = read(sockfd, inbuffer, sizeof(inbuffer));
            if (n > 0)
            {
                inbuffer[n] = 0;
                std::cout << inbuffer << std::endl;
            }
            // else break;
            // std::cout << "read return: " << n << std::endl;  // 测试
        // }

        close(sockfd); // 创建套接字在循环里，关闭文件描述符也得放在循环里
    }

    return 0;
}